require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const logger = require('./utils/logger');
const sequelize = require('./config/database');
const redis = require('./config/redis');
const _Admin = require('./models/Admin');
const _Certificate = require('./models/Certificate');
const _Field = require('./models/Field');
const _PermissionTemplate = require('./models/PermissionTemplate');
const _Department = require('./models/department');
const _swaggerUi = require('swagger-ui-express');
const _specs = require('./config/swagger');
const fileUpload = require('express-fileupload');
const uploadRoutes = require('./routes/upload');
const initDatabase = require('./config/init-db');
const { errorHandler } = require('./middleware/error');

// 路由
const adminRoutes = require('./routes/admin');
const certificateRoutes = require('./routes/certificate');
const fieldRoutes = require('./routes/field');
const importExportRoutes = require('./routes/importExport');
const systemRouter = require('./routes/system');
const departmentRoutes = require('./routes/department');
const permissionTemplateRoutes = require('./routes/permissionTemplate');
const userRoutes = require('./routes/users');

const app = express();

// 中间件
app.use(cors({
  exposedHeaders: ['Content-Disposition']
}));
app.use(express.json({
  limit: '50mb',
  type: ['application/json', 'text/plain']
}));
app.use(express.urlencoded({ 
  extended: true,
  limit: '50mb'
}));

/*
// 文件上传中间件 - 与 multer 冲突，暂时禁用
app.use(fileUpload({
  limits: { 
    fileSize: 5 * 1024 * 1024 // 5MB
  },
  useTempFiles: true,
  tempFileDir: path.join(__dirname, 'tmp'),
  debug: false,
  safeFileNames: true,
  preserveExtension: true,
  abortOnLimit: true,
  createParentPath: true,
  uploadTimeout: 0
}));
*/

// 静态文件服务
app.use('/api/uploads', express.static(path.join(__dirname, 'uploads'), {
  setHeaders: (res, filePath) => {
    if (path.extname(filePath) === '.png') {
      res.setHeader('Content-Type', 'image/png');
    } else if (path.extname(filePath) === '.jpg' || path.extname(filePath) === '.jpeg') {
      res.setHeader('Content-Type', 'image/jpeg');
    } else if (path.extname(filePath) === '.ico') {
      res.setHeader('Content-Type', 'image/x-icon');
    }
  }
}));

// 前端静态文件
app.use('/', express.static(path.join(__dirname, '../frontend/dist')));
app.use('/assets', express.static(path.join(__dirname, '../frontend/dist/assets')));

// 设置 API 响应头，确保中文正确显示
app.use('/api', (req, res, next) => {
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  res.setHeader('Accept-Charset', 'utf-8');
  next();
});

// API 路由
app.use('/api/admin', adminRoutes);
app.use('/api/certificates', certificateRoutes);
app.use('/api/fields', fieldRoutes);
app.use('/api/data', importExportRoutes);
app.use('/api/system', systemRouter);
app.use('/api/upload', uploadRoutes);
app.use('/api/departments', departmentRoutes);
app.use('/api/permission-templates', permissionTemplateRoutes);
app.use('/api/users', userRoutes);

// 处理前端路由
app.get('/view/*', (req, res) => {
  res.sendFile(path.join(__dirname, '../frontend/dist/index.html'));
});

// Swagger API 文档
app.use('/api-docs', _swaggerUi.serve, _swaggerUi.setup(_specs, {
  explorer: true,
  customCss: '.swagger-ui .topbar { display: none }',
  customSiteTitle: "证书管理系统 API 文档"
}));

// 使用自定义错误处理中间件
app.use(errorHandler);

// 未捕获的Promise异常处理
process.on('unhandledRejection', (reason, promise) => {
  logger.error('Unhandled Rejection at:', {
    promise,
    reason: reason instanceof Error ? {
      name: reason.name,
      message: reason.message,
      stack: reason.stack
    } : reason
  });
});

// 未捕获的异常处理
process.on('uncaughtException', (error) => {
  logger.error('Uncaught Exception:', {
    name: error.name,
    message: error.message,
    stack: error.stack
  });
});

// 初始化数据库
async function startServer() {
  try {
    // 清除所有Redis缓存以解决潜在的数据不一致问题
    await redis.flushall();
    logger.info('所有Redis缓存已成功清除。');

    // 测试数据库连接
    await sequelize.authenticate();
    logger.info('数据库连接成功');

    // 初始化数据库（包含表的创建和基础数据）
    await initDatabase();
      
    // 确保证书编号字段存在
    await _Field.ensureCertNumberField();
    logger.info('证书编号字段创建完成');
      
    // 创建根部门
    await _Department.createRootDepartment();
    logger.info('根部门创建完成');

    const PORT = process.env.PORT || 3800;
    app.listen(PORT, () => {
      logger.info(`服务器运行在端口 ${PORT}`);
    });
  } catch (error) {
    logger.error('服务器启动失败:', error);
    process.exit(1);
  }
}

startServer();

module.exports = app; 